<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { Search, Refresh } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"

import {
  getTbListDataApi,
  gettmqueryCardAPi,
  getTmReceivingInfo,
  getDetailsInfo,
  changeColor
} from "@/api/capture-tb/index"
import { createOrderDataApi } from "@/api/order"
import { type FormInstance, ElMessage, type FormRules } from "element-plus"
import { useUserStore } from "@/store/modules/user"
import useClipboard from "vue-clipboard3"
import { checkPhoneNumber, checkID, checkName } from "@/utils/validate"
import { shortcuts } from "@/utils/dateSet"

defineOptions({
  name: "CaptureListTb"
})

const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const userStore = useUserStore()

const loading = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)

// #region 查
const defaultTime1: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 0)]
const searchFormRef = ref<FormInstance | null>(null)

// 搜索内容
const searchData = reactive<any>({
  time: "",
  orderId: ""
})

const formRules: FormRules = reactive({
  idCardName: [{ required: true, validator: checkName, trigger: "blur" }],
  name: [{ required: true, validator: checkName, trigger: "blur" }],
  consignee: [{ required: true, validator: checkName, trigger: "blur" }],
  // handleMobile: [{ required: true, validator: checkPhoneNumber, trigger: "blur" }],
  idCard: [{ required: true, validator: checkID, trigger: "blur" }],
  mobile: [{ required: true, validator: checkPhoneNumber, trigger: "blur" }],
  address: [{ required: true, trigger: "blur", message: "请输入地址" }]
})

const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
// #endregion

const tableData = ref<any>([])
const getTableData = async () => {
  loading.value = true
  if (searchData.orderId) {
    await getDetailsInfo({
      orderId: searchData.orderId
    })
      .then((res: any) => {
        paginationData.total = 1
        if (res.data.trade_fullinfo_get_response.trade) {
          tableData.value = [res.data.trade_fullinfo_get_response.trade]
        } else {
          tableData.value = []
        }

        loading.value = false
      })
      .finally(() => {
        loading.value = false
      })
  } else {
    searchData.orderId = ""
    await getTbListDataApi({
      start: new Date(searchData.time[0]).getTime() / 1000 || null,
      end: new Date(searchData.time[1]).getTime() / 1000 || null,
      page: paginationData.currentPage,
      size: paginationData.pageSize
    })
      .then((res: any) => {
        paginationData.total = res.data.trades_sold_get_response.total_results
        if (res.data.trades_sold_get_response.trades) {
          tableData.value = res.data.trades_sold_get_response.trades.trade
        } else {
          tableData.value = []
        }

        loading.value = false
      })
      .finally(() => {
        loading.value = false
      })
  }
}

// #region 套餐
import { getComboDataApi } from "@/api/combo-jd"
const comboList = ref<any>([])
getComboDataApi({
  page: 1,
  size: 10000,
  type: "tb",
  userId: userStore.usernameID
}).then((res: any) => {
  comboList.value = res.data.list
})
// #endregion

// #region 查看详情
const formData = reactive<any>({ data: {} })
const seeState = ref<string>("")
const dialogVisible = ref<boolean>(false)
const isDiscard = ref<any>("否")
const detaildFnc = async (row: any) => {
  loading.value = true
  // 根据订单id查询身份证
  await gettmqueryCardAPi({
    orderId: row.tid
  }).then((res) => {
    row.idCard = res.data.alibaba_aliqin_tcc_trade_identity_newget_response?.module?.card_num
    row.idCardName = res.data.alibaba_aliqin_tcc_trade_identity_newget_response?.module?.name
  })
  //根据订单ID查详情（卖家备注）
  await getDetailsInfo({ orderId: row.tid }).then((res: any) => {
    row.remark2 = res.data.trade_fullinfo_get_response.trade.seller_memo
    row.remark3 = res.data.trade_fullinfo_get_response.trade.buyer_message
    // console.log(row.remark, 192)
  })
  //根据id查询收件信息
  await getTmReceivingInfo({ oaid: row.oaid, tid: row.tid })
    .then((res: any) => {
      if (res.data.error_response) {
        ElMessage.error(res.data.error_response.sub_msg)
        return false
      }
      if (!res.data.top_oaid_decrypt_response.receiver_list.receiver[0].district) {
        res.data.top_oaid_decrypt_response.receiver_list.receiver[0].district = ""
      }
      row.name = res.data.top_oaid_decrypt_response.receiver_list.receiver[0].name
      row.mobile = res.data.top_oaid_decrypt_response.receiver_list.receiver[0].mobile
      row.address = `${res.data.top_oaid_decrypt_response.receiver_list.receiver[0].state} ${res.data.top_oaid_decrypt_response.receiver_list.receiver[0].city} ${res.data.top_oaid_decrypt_response.receiver_list.receiver[0]?.district} ${res.data.top_oaid_decrypt_response.receiver_list.receiver[0].address_detail}`
    })
    .finally(() => {
      loading.value = false
    })
}
//查看详情
const handleSeeInfo = async (row: any) => {
  seeState.value = "see"
  await detaildFnc(row)
  rowData(row, false)
}
// row通用
const rowData = async (row: any, PL: boolean) => {
  formData.data = JSON.parse(JSON.stringify(row))
  if (!PL) {
    dialogVisible.value = true
    dataArr.value.push(formData.data)
  } else {
    dataArr.value.push(row)
  }
}

// #endregion

// #region 批量提交
const dataArr = ref<any>([])
const tableRef = ref<any>(null)

// 订单上传接口
const isHj = ref<any>(false)
const good_sku = ref<any>("")
const he_id = ref<any>("")
const pushDy = async (data: any) => {
  const datainfo = data[0]
  comboList.value.filter((item: any) => {
    if (item.code === datainfo.orders.order[0].sku_id) {
      good_sku.value = item.systemId ? item.systemId : ""
      he_id.value = item.heId ? item.heId : ""
      isHj.value = !!item.heId
    }
  })
  // console.log(isHj.value, "10234aaa")
  // return false
  if (!good_sku.value && !he_id.value) {
    ElMessage.warning("商品未与系统套餐做匹配，请先配置套餐!")
    return
  }
  // console.log(datainfo, isDiscard.value)
  await createOrderDataApi(
    {
      orderId: datainfo.tid,
      source: userStore.teamName || userStore.username,
      takeMobile: datainfo.mobile,
      cardName: datainfo.idCardName,
      cardId: datainfo.idCard,
      consignee: datainfo.idCardName,
      takeAddress: datainfo.address,
      remark: datainfo.remark,
      isDiscard: isDiscard.value,
      wantWant: datainfo.wantWant,
      sku: good_sku.value,
      heId: he_id.value
    },
    userStore.usernameID,
    isHj.value
  ).then((res: any) => {
    // console.log(res, 1923)
    if (res.code == 200) {
      dataArr.value = []
      tableRef.value?.clearSelection()
      ElMessage.success(res.message)
      dialogVisible.value = false

      changeFlagColor(datainfo.tid, 3)
      setTimeout(() => {
        getTableData()
      }, 1500)
    }
  })
}
//更改旗子颜色
const changeFlagColor = async (orderId: string, color: number) => {
  await changeColor({ orderId: orderId, color: color }).then((res: any) => {
    console.log(res)
  })
}

//单次提交
const handleAdd = async (row: any) => {
  await detaildFnc(row)
  rowData(row, false)
}

const isThrottle = ref(true) // 节流
const isThrottle2 = ref(false) // 按钮
const handlePushOne = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (isThrottle.value) {
        isThrottle.value = false
        isThrottle2.value = true
        pushDy(dataArr.value)
        setTimeout(() => {
          isThrottle.value = true
          isThrottle2.value = false
          console.log("可以点")
        }, 3000)
      } else {
        console.log("点不了")
      }
    } else {
      return false
    }
  })
}

// #endregion

//  #region 清除规则报错信息
const currentUpdateId = ref<undefined | string>(undefined)
const clearValidate = () => {
  formRef.value?.clearValidate()
}
const resetForm = () => {
  currentUpdateId.value = undefined
  isThrottle2.value = false
  formData.data = {}
  isDiscard.value = "否"
  seeState.value = ""
  dataArr.value = []
  clearValidate()
}
// #endregion

//复制套餐编码

const { toClipboard } = useClipboard()
const copy = async (text: string) => {
  try {
    await toClipboard(text) //实现复制
    ElMessage.success("已复制！")
  } catch (e) {
    console.error(e)
  }
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
// #endregion
</script>
<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper" v-loading="loading">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="orderId" label="订单ID">
          <el-input v-model.trim="searchData.orderId" clearable placeholder="请输入" style="width: 240px" />
        </el-form-item>
        <el-form-item prop="time" label="订单日期">
          <el-date-picker
            v-model="searchData.time"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            :default-time="defaultTime1"
          />
        </el-form-item>
        <!-- <el-form-item prop="status" label="状态">
          <el-select v-model="searchData.status" clearable placeholder="请选择" style="width: 200px">
            <el-option v-for="item in orderStatusList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="never" v-loading="loading">
      <div class="table-wrapper">
        <el-table :data="tableData" ref="tableRef">
          <el-table-column prop="tid" label="订单ID" align="center" />
          <el-table-column label="商品信息" align="center" width="300">
            <template #default="scope">
              <el-row>
                <el-col :span="8" style="text-align: center; vertical-align: middle">
                  <p><img :src="scope.row.orders.order[0].pic_path" alt="" width="60" height="60" /></p>
                </el-col>
                <el-col :span="16">
                  <p :title="scope.row.orders.order[0].sku_properties_name">
                    {{ scope.row.orders.order[0].sku_properties_name }}
                  </p>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column label="套餐匹配" align="center" width="360">
            <template #default="scope">
              <el-select v-model="scope.row.orders.order[0].sku_id" clearable filterable placeholder="请选套餐">
                <el-option v-for="item in comboList" :key="item.id" :label="item.systemName" :value="item.code" />
              </el-select>
              <el-link type="primary" style="margin-left: 10px" @click="copy(scope.row.orders.order[0].sku_id)"
                ><el-icon><DocumentCopy /></el-icon>复制编码</el-link
              >
            </template>
          </el-table-column>
          <el-table-column prop="created" label="订单创建时间" width="180" align="center" />
          <el-table-column label="收件信息" align="center">
            <template #default="scope">
              <p>{{ scope.row.receiver_name }}</p>
              <p>{{ scope.row.receiver_mobile }}</p>
              <p>
                {{ scope.row.receiver_state }} {{ scope.row.receiver_city }} {{ scope.row.receiver_district }}
                {{ scope.row.receiver_town }}
                {{ scope.row.receiver_address }}
              </p>
            </template>
          </el-table-column>
          <el-table-column prop="seller_flag" label="卖家备注(颜色)" align="center">
            <template #default="scope">
              <p>
                <span
                  class="flag"
                  :class="{
                    grey: scope.row.seller_flag == 0,
                    red: scope.row.seller_flag == 1,
                    yellow: scope.row.seller_flag == 2,
                    green: scope.row.seller_flag == 3,
                    blue: scope.row.seller_flag == 4,
                    purple: scope.row.seller_flag == 5
                  }"
                />
              </p>
              <!-- <p :title="scope.row.remark" class="esp">{{ scope.row.remark }}</p> -->
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleAdd(scope.row)" style="margin: 10px 0"
                >修改提交</el-button
              ><br />
              <el-button type="primary" text bg size="small" @click="handleSeeInfo(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="[10, 20]"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog v-model="dialogVisible" :title="seeState === 'see' ? '查看详情' : '提交'" @close="resetForm" width="60%">
      <el-form ref="formRef" :rules="formRules" :model="formData.data" label-width="100px" label-position="left">
        <el-form-item prop="tid" label="订单ID">
          <el-input v-model="formData.data.tid" placeholder="请输入订单编号" disabled />
        </el-form-item>
        <el-form-item prop="createTime" label="创建时间">
          <div class="el-input is-disabled">
            <div class="el-input__wrapper">
              <span class="el-input__inner">{{ formData.data.created }}</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item prop="wantWant" label="旺旺号">
          <el-input v-model="formData.data.wantWant" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="idCardName" label="用户姓名">
          <el-input v-model="formData.data.idCardName" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="idCard" label="身份证号">
          <el-input v-model="formData.data.idCard" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="isDiscard" label="是否废单">
          <el-select
            v-model="isDiscard"
            clearable
            filterable
            placeholder="请选择"
            style="width: 240px"
            :disabled="seeState === 'see'"
          >
            <el-option key="02110" label="否" value="否" />
            <el-option key="02111" label="是" value="是" />
          </el-select>
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input v-model="formData.data.remark" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="productName" label="套餐名">
          <el-select
            v-model="formData.data.orders.order[0].sku_id"
            clearable
            filterable
            placeholder="请选套餐"
            style="width: 100%"
          >
            <el-option v-for="item in comboList" :key="item.id" :label="item.systemName" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item prop="productPic" label="套餐主图">
          <div class="demo-image__preview">
            <el-image
              style="width: 100px; height: 100px"
              :src="formData.data.orders.order[0].pic_path"
              :zoom-rate="1.2"
              :initial-index="4"
              fit="cover"
            />
          </div>
        </el-form-item>
        <el-form-item prop="remark3" label="买家留言">
          <el-input v-model="formData.data.remark3" placeholder="请输入" disabled />
        </el-form-item>
        <el-form-item prop="remark2" label="卖家备注">
          <el-input v-model="formData.data.remark2" placeholder="请输入" disabled />
        </el-form-item>
        <!-- 这里要求收货人姓名也用身份证姓名代替 -->
        <el-form-item prop="name" label="收货人姓名">
          <el-input v-model="formData.data.idCardName" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="mobile" label="联系电话">
          <el-input
            v-model="formData.data.mobile"
            maxlength="11"
            show-word-limit
            placeholder="请输入"
            :disabled="seeState === 'see'"
          />
        </el-form-item>
        <div>
          <el-form-item prop="address" label="收货地址">
            <el-input
              type="textarea"
              v-model="formData.data.address"
              placeholder="请输入"
              :disabled="seeState === 'see'"
            />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button :loading="isThrottle2" type="primary" @click="handlePushOne" v-if="seeState !== 'see'"
          >确认</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  .btn {
    width: 100%;
    height: 100%;
    display: flex;
  }
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
:deep(.el-upload-list__item .el-icon--close-tip) {
  top: 20px;
  left: 10px;
  right: 0;
}
.doing {
  color: #b88230;
}
.error {
  color: red;
}
.success {
  color: #67c23a;
}
.again {
  color: #c45656;
}
:deep(.el-popper) {
  max-width: 50% !important;
}
.date-box {
  width: 340px !important;
}
.text-ellipsis {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 3;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}
</style>
<style>
.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
.pbox {
  line-height: 2em;
}
.flag {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
}
.red {
  background: red;
}
.yellow {
  background: rgb(255, 220, 0);
}
.green {
  background: green;
}
.blue {
  background: blue;
}
.purple {
  background: purple;
}
.grey {
  background: gray;
}
.goodInfo {
  text-align: left;
}
.esp {
  /* width: 180px; */
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  cursor: pointer;
}
</style>
